//渲染数据
async function renderStudent() {
    const { data: res } = await axios.get('/students')
    let arr = res.data.map(item => {
        return `
          <tr>
            <td>${item.name}</td>
            <td>${item.age}</td>
            <td>${item.gender === 0 ? '男' : '女'}</td>
            <td>第${item.group}组</td>
            <td>${item.hope_salary}</td>
            <td>${item.salary}</td>
            <td>${item.province} ${item.city} ${item.area}</td>
            <td>
              <a href="javascript:;" class="text-success mr-3"><i data-id='${item.id}' class="bi bi-pen"></i></a>
              <a href="javascript:;" class="text-danger"><i data-id='${item.id}' class="bi bi-trash"></i></a>
            </td>
          </tr>
          `
    })
    document.querySelector('tbody').innerHTML = arr.join('')
    document.querySelector('.total').innerHTML = arr.length
}
renderStudent()

//模态框使用
const addmodal = new bootstrap.Modal(document.querySelector('#modal'))
document.querySelector('#openModal').addEventListener('click', () => {
    document.querySelector('h5.modal-title').innerHTML = '添加学员'
    document.querySelector('#form').reset()
    addmodal.show()
})

//省市县联动
async function initCity() {
    const province = document.querySelector('[name=province]')
    const city = document.querySelector('[name=city]')
    const area = document.querySelector('[name=area]')
    //获取省
    const { data: res } = await axios.get('/api/province')
    let arr = res.data.map(item => `<option value="${item}">${item}</option>`)
    province.innerHTML = '<option value="">--省份--</option>' + arr.join('')
    //获取市
    province.addEventListener('change', async function () {
        let pname = province.value
        area.innerHTML = '<option value="">--地区--</option>'
        if (pname === '')
            return (city.innerHTML = '<option value="">--城市--</option>')
        const { data: res } = await axios.get('/api/city', { params: { pname } })
        let arr = res.data.map(item => `<option value="${item}">${item}</option>`)
        city.innerHTML = '<option value="">--城市--</option>' + arr.join('')
    })
    //获取区县
    city.addEventListener('change', async function () {
        let pname = province.value
        let cname = city.value
        if (cname === '')
            return (area.innerHTML = '<option value="">--地区--</option>')
        const { data: res } = await axios.get('/api/area', { params: { pname, cname } })
        let arr = res.data.map(item => `<option value="${item}">${item}</option>`)
        area.innerHTML = '<option value="">--地区--</option>' + arr.join('')
    })
}
initCity()

//添加功能
document.querySelector('#submit').addEventListener('click', async function (e) {
    e.preventDefault()
    let data = val(document.querySelector('#form'))
    data.age = +data.age
    data.gender = +data.gender
    data.group = +data.group
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    if (document.querySelector('h5.modal-title').innerHTML === '添加学员') {
        try {
            const { data: res } = await axios.post('/students', data)
            message.success(res.message)
            addmodal.hide()
            renderStudent()
            console.log(res)
        } catch (err) {
            message.error('添加失败')
        }
    }
    else {
        try {
            let id = document.querySelector('.modal-title').dataset.id
            const { data: res } = await axios.put(`/students/${id}`, data)
            message.success(res.message)
            addmodal.hide()
            renderStudent()
            console.log(res)
        } catch (err) {
            message.error('修改失败')
        }
    }

})

//删除和修改功能
document.querySelector('tbody').addEventListener('click', async function (e) {
    let id = e.target.dataset.id
    if (e.target.classList.contains('bi-trash')) {
        message.confirm('提示', '确定删除吗?', async res => {
            if (res) {
                try {
                    const { data: res } = await axios.delete(`/students/${id}`)
                    message.success('删除成功')
                    renderStudent()
                } catch (err) {
                    message.error('删除失败')
                }
            }
        })
    }
    if (e.target.classList.contains('bi-pen')) {
        addmodal.show()
        const { data: res } = await axios.get(`/students/${id}`)
        // console.log(res)
        document.querySelector('h5.modal-title').innerHTML = '修改学员'
        document.querySelector('h5.modal-title').setAttribute('data-id', id)
        let p1 = axios.get('/api/city', { params: { pname: res.data.province } })
        let p2 = axios.get('/api/area', { params: { pname: res.data.province, cname: res.data.city } })
        const [{ data: { data: c } }, { data: { data: a } }] = await Promise.all([p1, p2])
        let arr2 = c.map(item => `<option value="${item}">${item}</option>`)
        document.querySelector('[name=city]').innerHTML = '<option value="">--城市--</option>' + arr2.join('')
        let arr3 = a.map(item => `<option value="${item}">${item}</option>`)
        document.querySelector('[name=area]').innerHTML = '<option value="">--地区--</option>' + arr3.join('')
        val(document.querySelector('#form'), res.data)
    }
})